<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商城首页</title>
</head>
<body>
<h2>欢迎来到我的商城！</h2>
<div id="box">
    <template v-if="goods.length">
        <table border="1" cellspacing="0">
            <tr>
                <td>编号</td>
                <td>商品名称</td>
                <td>单价</td>
                <td>数量</td>
                <td>小计</td>
            </tr>
            <tr v-for="(it,i) in goods">
                <td>{{it.id}}</td>
                <td>{{it.name}}</td>
                <td>￥{{it.price}}</td>
                <td>
                    <button>-</button>{{it.selectCount}}<button
                        v-on:click="add(i)"
                        v-bind:disabled="goods[i].selectCount>=goods[i].count"
                >
                    +
                </button>
                </td>
                <td>￥{{it.xj}}</td>
            </tr>
        </table>
        <h3>您的商品总价为：{{total}},<button v-on:click="pay()">支付宝支付订单</button></h3>
    </template>
    <template v-else>
        <div>亲，本商城商品还没有上架，后台小哥正在上架中。。。。</div>
    </template>
</div>
<script src="./js/vue.js"></script>
<script src="./js/axios.js"></script>
<script>
    new Vue({
        el: "#box",
        methods: {
            add: function (x) {
                if (this.goods[x].selectCount < this.goods[x].count) {
                    this.goods[x].selectCount++;
                    this.goods[x].xj=this.goods[x].xj+this.goods[x].price;
                    this.total=this.total+this.goods[x].price;
                }
            },
            pay:function (){
                // 这里发起网络访问，将订单信息提交给后台接口，后台接口收到json数据进行分析，是否能满足订单要求，
                axios.post('/api/pay',this.goods)
                .then((res)=>{
                    // 这种写法es6，里面的this表是当前vue对象
                    console.log("支付成功！")
                }).catch((error)=>{
                    console.log('支付失败')
                })
            }
        },
        data: {
            goods: "",
            total: 0
        },
        mounted:function (){
            let that=this;
            //这里的代码是当这个vue对象生成完成时执行，所以在这里访问后端获取数据
            axios.get('/api/getAllGoods')
            .then(function (r){
                // 这里的this表示当前函数对象
                console.log(r)
                if(r.data.constructor==Array){
                    that.goods=r.data;
                    for(let i=0;i<that.goods.length;i++){
                        let obj=that.goods[i];
                        obj['xj']=0;
                        obj['selectCount']=0
                    }
                    console.log(that.goods.length);
                }else {
                    window.location.href="/login.html";
                }

            }).catch(function (error){
                console.log(error)
            })
        }
    });
</script>

</body>
</html>